package com.example.wxsmart.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.wxsmart.pojo.Question;
import com.example.wxsmart.pojo.Video;
import com.example.wxsmart.service.QuestionService;
import com.example.wxsmart.util.OkHttpUtil;
import com.example.wxsmart.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Luojunxian
 * @data 2022/8/22 16:56
 * @classname VideoResources
 */
@Slf4j
@Component
public class VideoResources {

    @Value("${video.data.source}")
    private String videoUrl;

    @Resource
    private QuestionService questionService;

    /**
     * 获取视频列表
     *
     * @return {@code List<Video>}
     */
    private List<Video> getVideoList() {
        log.info("===开始获取视频数据===");
        String sendGet = OkHttpUtil.sendGet(videoUrl);
        log.info("===获取视频数据完毕===");

        JSONObject jsonObject = JSON.parseObject(sendGet);

        JSONArray list = jsonObject.getJSONArray("list");

        List<Video> videoList = list.toJavaList(Video.class);

        return videoList;
    }

    /**
     * 视频问题列表
     *
     * @return {@code List<Question>}
     */
    private List<Question> getVideoQuestionList() {
        List<Question> result = new ArrayList<>();
        List<Video> videoList = getVideoList();

        videoList.forEach(o -> {
            Question question = Question.builder()
                    .id(o.getVod_id())
                    .question(o.getVod_name())
                    .answer(o.getVod_remarks())
                    .build();

            result.add(question);
        });

        return result;
    }

    public void saveOrUpdateVideoQuestion(){
        log.info("===开始同步视频数据===");
        long begin = System.currentTimeMillis();
        List<Question> videoQuestionList = getVideoQuestionList();

        List<Question> list = new ArrayList<>();
        int i = 0;
        for (Question question : videoQuestionList) {
            list.add(question);
            i++;

            if (i == 1000 || i == videoQuestionList.size()) {
                List<Question> finalList = list;
                questionService.addOrUpdateList(finalList);
                list = new ArrayList<>();
                i = 0;
            }
        }

        log.info("===视频数据同步完毕===");
        log.info("===共同步{}条数据===,花费 {} ", videoQuestionList.size(), TimeUtil.formatHourMinSecondMillisecond(System.currentTimeMillis() - begin));
    }

    public static void main(String[] args) {
        String sendGet = OkHttpUtil.sendGet("http://120.78.235.190/api.php/provide/vod/?ac=list");
        JSONObject jsonObject = JSON.parseObject(sendGet);

        List<Video> list = jsonObject.getObject("list", List.class);
        System.out.println();
    }
}
